﻿#region Disclaimer/Info

/////////////////////////////////////////////////////////////////////////////////////////////////
//
//   File:		AsyncCallInterceptor.cs
//   Website:		http://dexterblogengine.com/
//   Authors:		http://dexterblogengine.com/About.ashx
//   Rev:		1
//   Created:		19/01/2011
//   Last edit:		19/01/2011
//   License:		GNU Library General Public License (LGPL)
//   File:            AsyncCallInterceptor.cs
//   For updated news and information please visit http://dexterblogengine.com/
//   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
//   For any question contact info@dexterblogengine.com
//
///////////////////////////////////////////////////////////////////////////////////////////////////

#endregion

using System;
using Castle.DynamicProxy;
using Dexter.IoC.Castle;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.SessionFactory;

namespace Dexter.Dependency.Castle.Interceptors {
	/// <summary>
	/// 	This is the interceptor that intercepts the call of asyncserice
	/// 	and manage transacrtion.
	/// </summary>
	public class AsyncCallInterceptor : IInterceptor {
		readonly IDexterContainer container;

		ISessionFactory sessionFactory;
		ILogger logger;

		/// <summary>
		/// 	Initializes a new instance of the <see cref = "T:System.Object" /> class.
		/// </summary>
		public AsyncCallInterceptor ( IDexterContainer container ) {
			this.container = container;
		}

		internal ISessionFactory SessionFactory {
			get { return sessionFactory ?? ( sessionFactory = container.Resolve <ISessionFactory> ( ) ); }

			set { sessionFactory = value; }
		}

		internal ILogger Logger {
			get { return logger ?? ( logger = container.Resolve<ILogger> ( ) ); }

			set { logger = value; }
		}

		#region IInterceptor Members

		/// <summary>
		/// 	intercept the async call.
		/// </summary>
		/// <param name = "invocation"></param>
		public void Intercept ( IInvocation invocation ) {
			try {
				invocation.Proceed ( );
				SessionFactory.CloseCurrentSession ( true );
			}
			catch ( Exception ex ) {
				Logger.Error ( Utils.CreateInvocationLogString ( invocation ) , ex );
				SessionFactory.CloseCurrentSession ( false );
				//Note:is necessary to prevent the down of IIS
				//throw;
			}
		}

		#endregion
	}
}